package com.example.examsystem.controller;

import com.example.examsystem.dto.PageResponse;
import com.example.examsystem.model.LogLevel;
import com.example.examsystem.model.SystemLog;
import com.example.examsystem.service.SystemLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 系统日志控制器
 */
@RestController
@RequestMapping("/system/logs")
@RequiredArgsConstructor
public class SystemLogController {
    
    private final SystemLogService systemLogService;
    
    /**
     * 分页查询系统日志
     */
    @GetMapping
    @PreAuthorize("hasAuthority('system:log:view')")
    public ResponseEntity<PageResponse<SystemLog>> getLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) LogLevel level,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        
        PageResponse<SystemLog> logs = systemLogService.getLogs(
            page, size, username, level, action, startTime, endTime);
        return ResponseEntity.ok(logs);
    }
    
    /**
     * 清理过期日志
     */
    @DeleteMapping("/clean")
    @PreAuthorize("hasAuthority('system:log:clean')")
    public ResponseEntity<Void> cleanLogs(@RequestParam(defaultValue = "30") int days) {
        systemLogService.cleanExpiredLogs(days);
        return ResponseEntity.ok().build();
    }
}


